<?php

/**
 * 个人资料
 */

namespace app\member\common;

class SettingCommon extends \app\member\common\MemberCommon {

    protected function index() {
        if (!isPost()) {
            $this->setMeta('个人资料');
            $this->pageInfo['name'] = '个人资料';
            $this->assign('userInfo', $this->userInfo);
            $this->memberDisplay();
        } else {
            if (!target('member/Member', 'service')->updateUser($this->userInfo['user_id'], $_POST)) {
                $this->error(target('member/Member', 'service')->getError());
            } else {
                $this->success('资料修改成功!');
            }
        }
    }

    protected function avatar() {
        if (!isPost()) {
            $this->setMeta('修改头像');
            $this->pageInfo['name'] = '修改头像';
            $this->assign('userInfo', $this->userInfo);
            $this->memberDisplay();
        } else {
            $avatar = target('member/Member', 'service')->upload($this->userInfo['user_id'], 'jpg,jpeg,gif,png,bmp', 256, 256, false);
            if (!$avatar || empty($avatar['avatar'])) {
                $this->error(target('member/Member', 'service')->getError());
            }
            $data = [];
            $data['user_id'] = $this->userInfo['user_id'];
            $data['avatar'] = $avatar['avatar']['url'];
            if (!target('member/MemberUser')->edit($data)) {
                $this->error('头像修改失败!');
            }
            $this->success('头像修改成功!');
        }
    }

    protected function password() {
        if (!isPost()) {
            $this->setMeta('修改密码');
            $this->pageInfo['name'] = '修改密码';
            $this->assign('userInfo', $this->userInfo);
            $this->memberDisplay();
        } else {
            $post = request('post');
            $userInfo = target('member/MemberUser')->getInfo($this->userInfo['user_id']);
            if (md5($post['old_password']) <> $userInfo['password']) {
                $this->error('原始密码输入不正确!');
            }
            if (empty($post['password'])) {
                $this->error('请输入新密码!');
            }
            if ($post['password'] <> $post['password2']) {
                $this->error('两次密码输入不正确!');
            }
            $data = [];
            $data['user_id'] = $this->userInfo['user_id'];
            $data['password'] = md5($post['password']);
            if (!target('member/MemberUser')->edit($data)) {
                $this->error('密码修改失败!');
            }
            $this->success('密码修改成功!', url('member/Index/index'));
        }
    }

}